<?php
namespace App\Utility;
use EasySwoole\EasySwoole\Config as SystemConfig;
use EasySwoole\HttpClient\HttpClient;

class WechatService
{

    private static $instance = null;
    public  $wechat;
    private  $createQrcode = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";

    private function __construct($AppId ,$AppSecret ,$Token ,$AesKey)
    {
        $weChatConfig = new \EasySwoole\WeChat\Config();
        $weChatConfig->setTempDir(SystemConfig::getInstance()->getConf('TEMP_DIR'));
        $weChatConfig->officialAccount()->setAppId($AppId);
        $weChatConfig->officialAccount()->setAppSecret($AppSecret);
        $weChatConfig->officialAccount()->setToken($Token);
        $weChatConfig->officialAccount()->setAesKey($AesKey);
        $this->wechat = new \EasySwoole\WeChat\WeChat($weChatConfig);
        $this->wechat->officialAccount()->accessToken()->refresh();
    }

    public static function getInstance($AppId ,$AppSecret ,$Token ,$AesKey)
    {
        if(!isset(self::$instance[$AppId])){
            self::$instance[$AppId] = new self($AppId ,$AppSecret ,$Token ,$AesKey);
        }
        return self::$instance[$AppId];
    }

    /**
     * 创建公众号二维码
     * @param array $params 自定义参数
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function createQrcode($params = []){

        $token = $this->wechat->officialAccount()->accessToken()->getToken();
        $client = new \EasySwoole\HttpClient\HttpClient($this->createQrcode.$token);
        $response = $client->post(json_encode([
            'action_name' => 'QR_LIMIT_STR_SCENE',
            'action_info' => [
                'scene'=> [
                    'scene_str'=> json_encode($params)
                ]
            ]
        ]));

        $data = json_decode($response->getBody(),true);

        if(isset($data['errcode'])){
            return false;
        }

        $url = $data['url'];

        return $url ;

    }


}

?>